package com.renwei.yunlong.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.flyco.tablayout.SlidingTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.me.PasswordForgetActivity;
import com.renwei.yunlong.adapter.PagerViewAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.LoginBean;
import com.renwei.yunlong.bean.ServiceLoginBean;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.view.ImageViewWithStroke;
import com.zyf.fwms.commonlibrary.utils.SharedPreUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


/**
 * 登录页面
 * <p>
 * Created by Administrator on 2017/8/22.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, OnTabSelectListener {

    @Bind(R.id.iv_userheader)
    ImageViewWithStroke ivUserheader;
    @Bind(R.id.login_tab)
    SlidingTabLayout loginTab;
    @Bind(R.id.login_pager)
    ViewPager loginPager;
    @Bind(R.id.login_do_login)
    Button loginDoLogin;
    @Bind(R.id.login_foget)
    TextView loginFoget;
    @Bind(R.id.login_register)
    TextView loginRegister;
    @Bind(R.id.server_text)
    TextView serverText;
    @Bind(R.id.server_choose)
    TextView serverChoose;
    private EditText etServiceName, etServicePwd, etOwnerName, etOwnerPwd;
    private List<View> viewList = new ArrayList<>();
    private String thisCompanyType = "2";
    private String loginJson = "";
    String account = "";
    String password = "";
    private final String[] mTitles = {
            "服务商", "业主"
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        initView();
    }


    //初始化view
    @SuppressLint("CutPasteId")
    private void initView() {
        View ownerView = LayoutInflater.from(this).inflate(R.layout.layout_login_owner, null, false);
        View serviceView = LayoutInflater.from(this).inflate(R.layout.layout_login_owner, null, false);
        etOwnerName = ownerView.findViewById(R.id.user_name);
        etOwnerPwd = ownerView.findViewById(R.id.user_pwd);
        etServiceName = serviceView.findViewById(R.id.user_name);
        etServicePwd = serviceView.findViewById(R.id.user_pwd);
        etOwnerPwd.setFilters(new InputFilter[]{AppHelper.emojiFilter});
        etServicePwd.setFilters(new InputFilter[]{AppHelper.emojiFilter});
        loginDoLogin.setOnClickListener(this);
        loginFoget.setOnClickListener(this);
        loginRegister.setOnClickListener(this);
        serverChoose.setOnClickListener(this);
        viewList.add(serviceView);
        viewList.add(ownerView);
        PagerViewAdapter pagerViewAdapter = new PagerViewAdapter(viewList, this);
        loginPager.setAdapter(pagerViewAdapter);
        loginTab.setViewPager(loginPager, mTitles);
        loginJson = StringUtils.value(getIntent().getStringExtra("loginJson"));
        loginTab.setOnTabSelectListener(this);
        // 当账号为空时  密码也需要清空
        etOwnerName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(charSequence.toString())) {
                    etOwnerPwd.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        etServiceName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(charSequence.toString())) {
                    etServicePwd.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });

        etServiceName.post(new Runnable() {
            @Override
            public void run() {
                LogUtil.e("宽度" + etServiceName.getWidth());
                LogUtil.e("高度" + etOwnerName.getHeight());
            }
        });
        initDataFromCache();
        firstLogin();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initServerApi();
    }

    /**
     * 配置服务器信息
     */
    private void initServerApi() {
        initApi();
        if (info != null) {
            serverText.setText("已经连接" + info.getServerName() + "网络");
        }
    }


    private void firstLogin() {
        if (loginJson.length() != 0) {
            LogUtil.e("注册页面跳转过来带的json--:" + loginJson);
            HashMap map = (HashMap) JsonMapUtil.Json2Map(loginJson);
            ServiceRequestManager manager = ServiceRequestManager.getManager();
            manager.LoginAndQueryInfo(this, String.valueOf(map.get("companyType")), loginJson, this);
        }
    }


    @Override
    public void onClick(View v) {
        thisCompanyType = loginTab.getCurrentTab() == 0 ? "2" : "1";
        switch (v.getId()) {
            case R.id.login_do_login:
                if ("1".equals(thisCompanyType)) {
                    account = etOwnerName.getText().toString();
                    password = etOwnerPwd.getText().toString();
                } else if ("2".equals(thisCompanyType)) {
                    account = etServiceName.getText().toString();
                    password = etServicePwd.getText().toString();
                } else {
                    LogUtil.e("登录数据获取错误");
                }
                doLogin(account, password, thisCompanyType);
                break;
            case R.id.login_foget:
                PasswordForgetActivity.openForgetPwdActivity(this, thisCompanyType);
                break;
            case R.id.login_register:
                RegisterActivity.openRegisterActivity(this);
                break;
            case R.id.server_choose:
                ServerListActivity.openActivity(this);
                break;
            default:
                break;
        }
    }


    @Override
    public void onSuccess(int requestId, String result) {
        Intent intent;
        showCenterSuccessMsg("登陆成功");
        switch (requestId) {
            case 1://服务商
                ServiceLoginBean serviceBean = new Gson().fromJson(result, ServiceLoginBean.class);
                if (serviceBean.getMessage().getCode() == 200) {//登录成功
                    String avatar = Api.$().SERVICE_FILE_URL + serviceBean.getRows().getAvatar();
                    cacheData("2", avatar, account, password, serviceBean);
                    intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    this.finish();
                } else {
                    showCenterInfoMsg(serviceBean.getMessage().getMessage());
                }
                break;
            case 2://业主
                LoginBean ownerBean = new Gson().fromJson(result, LoginBean.class);
                if (ownerBean.getMessage().getCode() == 200) {//登录成功
                    String avatar = Api.$().OWNER_FILE_URL + ownerBean.getRows().getAvatar();
                    cacheData("1", avatar, account, password, ownerBean);
                    intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    this.finish();
                } else {
                    showCenterInfoMsg(ownerBean.getMessage().getMessage());
                }
                break;
            default:
                break;
        }
    }

    //从缓存中取得上次登录页面信息
    public void initDataFromCache() {
        String servName = SharedPreUtil.getString(this, "service_mobile", "");
        String servPwd = SharedPreUtil.getString(this, "service_pwd", "");
        String servIcon = SharedPreUtil.getString(this, "service_avatar", "");
        String ownerName = SharedPreUtil.getString(this, "owner_mobile", "");
        String ownerPwd = SharedPreUtil.getString(this, "owner_pwd", "");
        String ownerIcon = SharedPreUtil.getString(this, "owner_avatar", "");
        thisCompanyType = SharedPreUtil.getString(this, "default_company_type", "2");
        etServiceName.setText(servName);
        etServiceName.setSelection(servName.length());
        etServicePwd.setText(servPwd);
        etServicePwd.setSelection(servPwd.length());
        etOwnerName.setText(ownerName);
        etOwnerName.setSelection(ownerName.length());
        etOwnerPwd.setText(ownerPwd);
        etOwnerPwd.setSelection(ownerPwd.length());
        loginTab.setCurrentTab("2".equals(thisCompanyType) ? 0 : 1);
        if (servIcon.length() > 0 && "2".equals(thisCompanyType)) {
            Glide.with(this).load(servIcon).error(R.mipmap.login_icon).into(ivUserheader);
        } else if (ownerIcon.length() > 0 && "1".equals(thisCompanyType)) {
            Glide.with(this).load(ownerIcon).error(R.mipmap.login_icon).into(ivUserheader);
        }

    }

    //将登录成功后的相关信息存在缓存中
    public void cacheData(String companyType, String avatar, String mobile, String pwd, Serializable object) {
        SharedPreUtil.saveString(this, "default_company_type", companyType);
        if ("1".equals(companyType)) {
            mCache.put("loginBean", object);
            mCache.put("companyType", "1");
            SharedPreUtil.saveString(this, "owner_avatar", avatar);
            SharedPreUtil.saveString(this, "owner_mobile", mobile);
            SharedPreUtil.saveString(this, "owner_pwd", pwd);
        } else if ("2".equals(companyType)) {
            mCache.put("serviceLoginBean", object);
            mCache.put("companyType", "2");
            SharedPreUtil.saveString(this, "service_avatar", avatar);
            SharedPreUtil.saveString(this, "service_mobile", mobile);
            SharedPreUtil.saveString(this, "service_pwd", pwd);
        } else {
            LogUtil.e("mCache数据存放失败");
        }
    }


    public void doLogin(String userName, String pwd, String companyType) {
        showCenterInfoMsg("正在配置服务器信息。。。");

        showCenterInfoMsg("正在登陆。。。");
        LogUtil.e("登录类型" + companyType + "用户名" + userName + "密码" + pwd);
        if (StringUtils.value(userName).length() == 0) {
            showCenterInfoMsg("账号不能为空");
            return;
        }
        if (StringUtils.value(pwd).length() == 0) {
            showCenterInfoMsg("密码不能为空");
            return;
        }
        HashMap loginMap = new HashMap();
        loginMap.put("userName", userName);
        loginMap.put("password", pwd);
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        manager.LoginAndQueryInfo(this, companyType, JsonMapUtil.mapToJson(loginMap), this);
    }

    @Override
    public void onException(int requestId, String code) {
        if (code.contains("UnknownHostException")) {
            showTopWrongMsg("登陆失败\r 无法找到对应服务器");
        } else if (code.contains("SSLPeerUnverifiedException")) {
            showTopWrongMsg("登陆失败\r 服务器安全验证失败");
        } else if (code.contains("IllegalArgumentException") || code.contains("MalformedURLException")) {
            showTopWrongMsg("登陆失败\r 服务器地址错误");
        } else if (code.contains("java.net.ConnectException") || code.contains("erroCode:404")) {
            showTopWrongMsg("登陆失败\r 服务器异常");
        } else {
            showTopWrongMsg("登陆失败");
        }

    }


    public static void openLoginActivity(Context context) {
        context.startActivity(new Intent(context, LoginActivity.class));
    }

    /**
     * 第一次登录时候时候调用
     *
     * @param context
     * @param loginJson 登录使用的json
     */
    public static void openLoginActivityFirstLogin(Context context, String loginJson) {
        LogUtil.e("注册页面到登录页面跳转过来的json ---：" + loginJson);
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra("loginJson", loginJson);
        context.startActivity(intent);
    }

    @Override
    public void onTabSelect(int position) {
        thisCompanyType = position == 0 ? "2" : "1";
        String servIcon = SharedPreUtil.getString(this, "service_avatar", "");
        String ownerIcon = SharedPreUtil.getString(this, "owner_avatar", "");
        if ("2".equals(thisCompanyType) && !TextUtils.isEmpty(servIcon)) {
            Glide.with(this).load(servIcon).error(R.mipmap.icon_header_default).into(ivUserheader);
        } else if ("1".equals(thisCompanyType) && !TextUtils.isEmpty(ownerIcon)) {
            Glide.with(this).load(ownerIcon).error(R.mipmap.icon_header_default).into(ivUserheader);
        } else {
            Glide.with(this).load(R.mipmap.login_icon).into(ivUserheader);
        }

    }

    @Override
    public void onTabReselect(int position) {

    }
}



